﻿using Caliburn.Micro;
using MCPlatform.Builder.WorkStation.StationEvents;
using MCPlatform.Builder.WorkStation.StationEvents.Cutting;
using MCPlatform.Builder.WorkStation.StationEvents.Load;
using MCPlatform.Models;
using MCPlatform.MotionLib.Base;
using MCPlatform.UI.Controls.Models;
using netDxf.Entities;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace MCPlatform.Builder.WorkStation
{
    public class LoadStation : WorkStationBase,IHandle<CuttingToLoadEvent>
    {

        #region Properties
        public IMotion LoadDragAxis { get; set; }
        public IValve PullDragValve { get; set; }

        public IValve LoadJackValve { get; set; }

       // public IValve BlockValve { get; set; }

        public IIO HaveDutSensor { get; set; }

    
        public PointSettingModel PreMoveTime { get; set; }

        public PointSettingModel DragVelRate { get; set; }



        #endregion

        #region Fields

       // private bool isStarted = false;

        private bool isLoading = false;

        private bool isRunning = false;

        private bool isClearing = false;

       

        #endregion

        #region Events

      
     
        #endregion

        #region CTOR

        private static LoadStation? instance;
        private static readonly object lockObject = new object();

    
        public static LoadStation Instance
        {
            get
            {
                lock (lockObject)
                {
                    if (instance == null)
                    {
                        instance = new LoadStation();
                    }
                    return instance;
                }
            }
        }


        private LoadStation() 
        {
            //1.映射基本信息
            WorkStationModel = WorkStation.Instance.WorkStationDic[1];
           

            //3.获取单个信息至工位
            LoadDragAxis = AxisModels[0].MotionEntity!;
            LoadJackValve = CylinderModels[0].ValveEntity!;
            PullDragValve = CylinderModels[1].ValveEntity!;
          


            HaveDutSensor = IOModels[0].IOEntity!;
           


            PreMoveTime = PointSettingModels[0];

            DragVelRate = PointSettingModels[1];




        }

      
        public override void RegisterEvent()
        {
            
           
        }



        #endregion

        #region Event handler


        public async Task HandleAsync(CuttingToLoadEvent message, CancellationToken cancellationToken)
        {
            try
            {
                if (message.MessageType == MessageType.NotifyDrag)
                {
                    if (message.Message != null)
                    {
                        double vel = (double)message.Message;

               
                        LoadDragAxis.SetVelocity(vel * DragVelRate.Parameter);
                    }

                    double dis = 2000;
                    if (message.CustomMessage != null)
                    {
                        dis = (double)message.CustomMessage;
                    }

                    //先走一小段
                    LoadDragAxis.RelMove(2 * dis);
                    await Task.Delay((int)PreMoveTime.Parameter);
                   

                    message.TaskCompletionSource.SetResult(true);


                }
                else if (message.MessageType == MessageType.NotifyStopDrag)
                {
                    LoadDragAxis.StopMove();
                    message.TaskCompletionSource.SetResult(true);
                }
                else if (message.MessageType == MessageType.NotifyDone)
                {
                    await DryRun();
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                StopTrigger(isSetAbortedStatus:false);
              
                return;
                
            }
            
           

           // return Task.CompletedTask;
        }





        #endregion


        #region Methods

        public override async Task<bool> IsSaftyToMove()
        {
            try
            {              
                await Task.Delay(1);
                return true;
            }
            catch (Exception)
            {
                
                throw;
            }
            

        }


        public override async Task Initial()
        {
            try
            {
              
                 isClearing = false;

                 isLoading = false;




                await Task.Run(() =>
                {
                    //0.有料位有信号不能回原
                    // await IsSaftyToMove();
                    //1.全部轴使能
                    SetAllAxisEnable();

                    //2.全部气缸回原位
                    // await SetAllValvesBasing();

                    //3.电机回原
                    // await SetAllAxisHome(true);

                    //4.电机去等待位
                    // await AbsMoveAsync(LoadDragAxis, LoadWaitPos);

                    LogModel.LogInfo = "初始化完成！";
                    LogModel.Status = Shared.Enums.WorkStationStatus.Idle;



                }, cancellationToken);
            }
            catch (Exception)
            {

                throw;
            }
           
           

        }

        public override async Task DryRun()
        {
            try
            {
                isRunning = true;
                LogModel.Status = Shared.Enums.WorkStationStatus.Execute;

            //1.先走一段距离，等待到位传感器到位
            //await RelMoveAsync(LoadDragAxis,new PointSettingModel() { Parameter=300});
            //2.等待检测到位传感器到达
            Retry:
                var result = await WaitInputSignalIn(HaveDutSensor, true);
                //3.如果未检测到，报警提示
                if (!result.Item1)
                {
                    MessageBoxResult res = RetryEventTrigger("未检测到皮革！,是否重试？");
                    if (res == MessageBoxResult.No)
                    {
                        return;
                    }
                    else if (res == MessageBoxResult.Yes)
                    {
                        goto Retry;
                    }

                }

                ReadyEventTrigger(this, new LoadToCuttingEvent() { MessageType = MessageType.NotifyReady });

               
            }
            catch (Exception)
            {             
                throw;
            }
            finally{ isRunning = false; }

        }


        public override Task Clear(bool isClear)
        {
            return Task.CompletedTask;
        }

        public override async Task Execute()
        {
            await Task.Delay(1000);
        }

        
        
        public override   Task Test()
        {
            //GetAllAxesAndValveStatus();
            //var res = ResumnBeforeCheckStatus();
            return Task.CompletedTask;
        }

        public override Task ResetSignal()
        {            
            PauseEventSource.Set();
            SingleStepCompleteEvent.Set();
            isRunning = false;
            return Task.CompletedTask;
        }


        public override void StationStop()
        {
            ;
        }

        #endregion


    }
}
